package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import redstone.xmlrpc.XmlRpcFault;

import net.bican.wordpress.Wordpress;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

public class GetAutoContentServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String blog = (String) session.getAttribute("work");
		
		if(blog==null)
		{
			try {
				response.sendRedirect("/manager-blog");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		DBCollection coll = Data.data("blogCraw");
		DBObject object = coll.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		
		if(object.get("type").toString().equals("wordpress"))
		{
			ArrayList<String> category = Utils.returnCategory(object);
			request.setAttribute("category", category);
		}
		DBCollection collection = Data.data("urlCraw");
		DBCursor cursor=collection.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		request.setAttribute("cursor", cursor);
		
		String[] listError = new String[5];
		request.setAttribute("listError", listError);
		request.setAttribute("object", object);
		
		try {
			request.getRequestDispatcher("/get-auto-content.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unused")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String blog = (String) session.getAttribute("work");
		
		if(blog==null)
		{
			try {
				response.sendRedirect("/manager-blog");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String sitemap = request.getParameter("sitemap");
		String reglink = request.getParameter("reglink");
		String regtitle = request.getParameter("regtitle");
		String regcontent = request.getParameter("regcontent");
		String regremove = request.getParameter("regremove");
		String type = request.getParameter("type");
		String typeLink = request.getParameter("typeLink");
		String source = request.getParameter("source");
		String source_type = request.getParameter("source_type");
		String category = request.getParameter("category");
		String tag = request.getParameter("tag");
		String translate = request.getParameter("translate");
		String rewriter_title = request.getParameter("rewriter_title");
		String language = request.getParameter("language");
		String sumtitlebefore = request.getParameter("sumtitlebefore");
		String sumtitleafter = request.getParameter("sumtitleafter");
		String source_image = request.getParameter("source_image");
		String remove_tag_a = request.getParameter("remove_tag_a");
		String contain = request.getParameter("contain");
		
		ArrayList<String> site = Utils.getStachSite();
		
		sitemap = Utils.fomatSitemap(sitemap);
		
		String[] listError = new String[5];
		if(sitemap!=null&&sitemap.equals(""))
			listError[0]="Url is not empty !";
		if(reglink!=null&&reglink.equals(""))
			listError[1]="Regexp get link is not empty !";
		if(regtitle!=null&&regtitle.equals(""))
			listError[2]="Regexp title  is not empty !";
		if(regcontent!=null&&regcontent.equals(""))
			listError[3]="Regexp content is not empty !";
		if(site.contains(Utils.fomatDmain(sitemap))&&tag!=null&&tag.equals(""))
			listError[1]="Tag is not empty !";
		
		DBCollection collection = Data.data("urlCraw");
		
		DBCollection coll = Data.data("blogCraw");
		DBObject object = coll.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		
		
		if(listError[0]==null&&listError[1]==null&&listError[3]==null&&listError[2]==null)
		{
			DBObject object1 = collection.findOne(new BasicDBObject("sitemap",sitemap).append("username", dbObject.get("username")).append("blogurl", blog));
			
			int maxcout = 1500;
//			if(object.get("paysuccess")!=null&&"yes".equals(object.get("paysuccess").toString()))
//			{
//				maxcout = 40;
//			}
//			if(object.get("add")!=null&&!object.get("add").toString().equals(""))
//			{
//				maxcout=maxcout+20*Integer.parseInt(object.get("add").toString());
//			}
			int cout=1;
//			int cout = collection.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog)).count();
			
			if(cout<maxcout)
			{
				if(object1==null)
				{
					BasicDBObject basicDBObject = new BasicDBObject();
					
					if(site.contains(Utils.fomatDmain(sitemap)))
					{
						sitemap="http://"+Utils.fomatDmain(sitemap)+"/questions/tagged/"+tag;
						basicDBObject.put("tag", tag);
					}
					
					basicDBObject.put("username", dbObject.get("username").toString());
					basicDBObject.put("sitemap", sitemap);
					basicDBObject.put("reglink", reglink);
					basicDBObject.put("regtitle", regtitle);
					basicDBObject.put("regcontent", regcontent);
					basicDBObject.put("regremove", regremove);
					basicDBObject.put("domain", Utils.fomatDmain(sitemap));
					basicDBObject.put("type", type);
					basicDBObject.put("typeLink", typeLink);
					basicDBObject.put("source", source);
					basicDBObject.put("source_type", source_type);
					basicDBObject.put("category", category);
					basicDBObject.put("blogurl", blog);
					basicDBObject.put("status", "true");
					basicDBObject.put("active_craw", "yes");
					basicDBObject.put("translate", translate);
					basicDBObject.put("rewriter_title", rewriter_title);
					basicDBObject.put("language", language);
					basicDBObject.put("sumtitlebefore", sumtitlebefore);
					basicDBObject.put("sumtitleafter", sumtitleafter);
					basicDBObject.put("time", new Date().getTime());
					basicDBObject.put("source_image", source_image);
					basicDBObject.put("remove_tag_a", remove_tag_a);
					basicDBObject.put("contain", contain);
					basicDBObject.put("timeend", Long.parseLong(object.get("timeend").toString()));
					
					collection.insert(basicDBObject);
					request.setAttribute("success", "Add link success");
				} else {
					listError[4] = "Url already exists";
					request.setAttribute("sitemap", sitemap);
					request.setAttribute("reglink", reglink);
					request.setAttribute("regtitle", regtitle);
					request.setAttribute("regcontent", regcontent);
					request.setAttribute("regremove", regremove);
					request.setAttribute("type", type);
					request.setAttribute("typeLink", typeLink);
					request.setAttribute("source", source);
					request.setAttribute("source_type", source_type);
					request.setAttribute("category", category);
					request.setAttribute("translate", translate);
					request.setAttribute("rewriter_title", rewriter_title);
					request.setAttribute("sumtitlebefore", sumtitlebefore);
					request.setAttribute("sumtitleafter", sumtitleafter);
					request.setAttribute("source_image", source_image);
					request.setAttribute("remove_tag_a", remove_tag_a);
					request.setAttribute("contain", contain);
				}
			} else {
				listError[4] = "You only add a maximum of "+maxcout+" sources for one blog";
				request.setAttribute("sitemap", sitemap);
				request.setAttribute("reglink", reglink);
				request.setAttribute("regtitle", regtitle);
				request.setAttribute("regcontent", regcontent);
				request.setAttribute("regremove", regremove);
				request.setAttribute("type", type);
				request.setAttribute("typeLink", typeLink);
				request.setAttribute("source", source);
				request.setAttribute("source_type", source_type);
				request.setAttribute("category", category);
				request.setAttribute("translate", translate);
				request.setAttribute("rewriter_title", rewriter_title);
				request.setAttribute("sumtitlebefore", sumtitlebefore);
				request.setAttribute("sumtitleafter", sumtitleafter);
				request.setAttribute("source_image", source_image);
				request.setAttribute("remove_tag_a", remove_tag_a);
				request.setAttribute("contain", contain);
			}
		} else {
			request.setAttribute("sitemap", sitemap);
			request.setAttribute("reglink", reglink);
			request.setAttribute("regtitle", regtitle);
			request.setAttribute("regcontent", regcontent);
			request.setAttribute("regremove", regremove);
			request.setAttribute("type", type);
			request.setAttribute("typeLink", typeLink);
			request.setAttribute("source", source);
			request.setAttribute("source_type", source_type);
			request.setAttribute("category", category);
			request.setAttribute("translate", translate);
			request.setAttribute("rewriter_title", rewriter_title);
			request.setAttribute("sumtitlebefore", sumtitlebefore);
			request.setAttribute("sumtitleafter", sumtitleafter);
			request.setAttribute("source_image", source_image);
			request.setAttribute("remove_tag_a", remove_tag_a);
			request.setAttribute("contain", contain);
		}
		
		DBCursor cursor=collection.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog)).limit(100);
		request.setAttribute("cursor", cursor);
		
		
		request.setAttribute("listError", listError);
		request.setAttribute("post", "post");
		
		
		
		if(object.get("type").toString().equals("wordpress"))
		{
			ArrayList<String> categoryss = Utils.returnCategory(object);
			
			String[] listCategory = category.split(",");
			if(category!=null&&"".equals(category))
			{
				for (int i = 0; i < listCategory.length; i++) {
					int k=0;
					for (int j = 0; j < categoryss.size(); j++) {
						if(categoryss.get(j).equals(listCategory[i]))
						{
							k=1;
						}
					}
					if(k==0)
					{
						String username = object.get("usernameblog").toString();
					    String password = object.get("passwordblog").toString();
					    String xmlRpcUrl = object.get("blogurl").toString()+"/xmlrpc.php";
					    Wordpress wp = new Wordpress(username, password, xmlRpcUrl);
					    try {
							wp.newCategory(listCategory[i], listCategory[i], 0);
						} catch (XmlRpcFault e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			request.setAttribute("category", categoryss);
		}
		request.setAttribute("object", object);
		try {
			request.getRequestDispatcher("/get-auto-content.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		}
}
